package NIO;

import org.apache.logging.log4j.message.Message;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 47868
 */
public class 阻塞式网络通信服务端 {
    public static void print(Object msg) {
        System.out.println(msg);
    }
    public static void main(String[] args)throws Exception {
            ByteBuffer buffer = ByteBuffer.allocate(16);
            ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
            serverSocketChannel.bind(new InetSocketAddress(8080));
            List<SocketChannel> channels=new ArrayList<>();
            while (true){
                print("connecting...");
                SocketChannel socketChannel = serverSocketChannel.accept();
                print("connected..."+socketChannel);
                channels.add(socketChannel);
                for(SocketChannel s:channels){
                    print("before read..."+s);
                    while (true){
                        int bytesRead = s.read(buffer);
                        if (bytesRead > 0) {
                            buffer.flip();
                            byte[] bytes = new byte[buffer.limit()];
                            buffer.get(bytes);
                            String message = new String(bytes, StandardCharsets.UTF_8);
                            if("exit".equals(message)){
                                s.close();
                                break;
                            }
                            print(message);
                            buffer.clear();
                        }
                        buffer.clear();
                    }
                    print("after read..."+s);
                }
            }
    }
}
